package com.cortex.pineapple.fetch;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.cortex.pineapple.utilities.MessagesLog;
import com.cortext.pineapple.link.Link;
import com.cortext.pineapple.link.NewsLink;
import com.cortext.pineapple.link.NewsLink;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.util.Log;



public class FetchImages {

	private OnFetchImageChangedListener onFetchImageChangedListener;
	private StartImagesThread startImagesThread;

	public void startFetching(List<Link> links){
		if(isRunning()){
			startImagesThread.cancel(true);
		}
		startImagesThread = new StartImagesThread();
		startImagesThread.execute(links);
	}
	public void cancelFetching() {
		if(isRunning()){
			startImagesThread.cancel(true);
		}
	}
	public boolean isRunning(){
		return (startImagesThread != null)&&(startImagesThread.getStatus() == Status.RUNNING)?true:false;
	}
	public void setOnFetchImageChangedListener(OnFetchImageChangedListener onFetchImageChangedListener) {
		this.onFetchImageChangedListener = onFetchImageChangedListener;
	}
	private class StartImagesThread extends AsyncTask<List<Link>, LinkWithImage, List<Link>>{

		private Document doc;

		@Override
		protected List<Link> doInBackground(List<Link>... params) {
			List<Link> links = params[0];
			Elements elementsImages;
			for (Link link : links) {
				try {
					elementsImages = connectToUrl(link.getUrl());
					for (Element image : elementsImages) {
 						String src = image.absUrl("src");
						Attributes att = image.attributes();
						try{
							int width = Integer.parseInt(att.get("width"));
							int height = Integer.parseInt(att.get("height"));
							if(width > 100 && height > 100){
								onProgressUpdate(new LinkWithImage(link,src));
								break;
							}
						}
						catch(NumberFormatException e){
							Log.d(MessagesLog.APPLICATION_EXCEPTION,"throw exception when the width or height of image not a number message:" + e.getMessage());
						}
					}
					Thread.sleep(10);
				} catch (IOException e) {
					Log.d(MessagesLog.APPLICATION_EXCEPTION,"throw exception when connect to url message:" + e.getMessage());
				} catch (InterruptedException e) {
					Log.d(MessagesLog.APPLICATION_EXCEPTION,"throw exceptiob when thread sleeping message:" + e.getMessage());
				}
			}


			Log.d(MessagesLog.APPLICATION,"" + "application finished download all images from web site.");
			return links;
		}
		@Override
		protected void onPreExecute() {
			if(onFetchImageChangedListener != null){
				onFetchImageChangedListener.timeLoadImageStarted();
			}
		}

		@Override
		protected void onProgressUpdate(LinkWithImage... values) {
			Link link = values[0].getLink();
			if(link instanceof NewsLink){
				NewsLink newsLink = (NewsLink)link;
				newsLink.setImageUrl(values[0].getImageUrl());
			}
		}
		@Override
		protected void onPostExecute(List<Link> links) {
			if(onFetchImageChangedListener != null){
				onFetchImageChangedListener.timeLoadImageFinished(links);
			}
		}
		@Override
		protected void onCancelled() {
			if(onFetchImageChangedListener != null){
				onFetchImageChangedListener.timeLoadImageCancelled();
			}
		}
		private Elements connectToUrl(String url) throws IOException{
			doc = Jsoup.connect(url).get();
			return doc.select("img[src~=(?i)\\.(png|jpe?g|gif)]");
		}

	}

	public interface OnFetchImageChangedListener{
		void timeLoadImageStarted();
		void timeLoadImageFinished(List<Link> links);
		void timeLoadImageCancelled();
	}

	private class LinkWithImage{
		private Link link;
		private String url;

		public LinkWithImage(Link link, String url) {
			super();
			this.link = link;
			this.url = url;
		}

		public Link getLink() {
			return link;
		}
		public void setLink(Link link) {
			this.link = link;
		}
		public String getImageUrl() {
			return url;
		}
		public void setImageUrl(String url) {
			this.url = url;
		}

	}
}
